package com.cy.account.tcc;

import com.cy.account.entity.Account;
import com.cy.account.mapper.AccountMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Component
public class AccountTccActionImpl implements AccountTccAction {

    @Autowired
    private AccountMapper accountMapper;


    @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx, Long userId, BigDecimal money) {
        Account account = accountMapper.selectById(userId);
        /*if (account.getResidue().compareTo(money) < 0){
            throw new RuntimeException("可用金额不足");
        }*/

        if (account.getResidue().intValue() < money.intValue()){
            throw new RuntimeException("可用金额不足");
        }

        accountMapper.updateResidueToFrozen(userId,money);

        ResultHolder.setResult(AccountTccAction.class,ctx.getXid(),"p");
        return true;
    }

    @Transactional
    @Override
    public boolean commit(BusinessActionContext ctx) {
        if (ResultHolder.getResult(AccountTccAction.class,ctx.getXid()) == null){
            return true;
        }

        accountMapper.updateFrozenToUsed(
                Long.valueOf(ctx.getActionContext("userId").toString()),
                new BigDecimal(ctx.getActionContext("money").toString()));

        ResultHolder.removeResult(AccountTccAction.class,ctx.getXid());

        return true;
    }

    @Transactional
    @Override
    public boolean rollback(BusinessActionContext ctx) {
        if (ResultHolder.getResult(AccountTccAction.class,ctx.getXid()) == null){
            return true;
        }

        accountMapper.updateFrozenToResidue(
                Long.valueOf(ctx.getActionContext("userId").toString()),
                new BigDecimal(ctx.getActionContext("money").toString()));

        ResultHolder.removeResult(AccountTccAction.class,ctx.getXid());

        return true;
    }
}
